 package com.example.weight.greenSeasons.researchDevelopment;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.Item;
import com.example.weight.arrayAdapter.ItemAdapter;
import com.example.weight.config.Config;
import com.example.weight.util.WeightActivity;

import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

public class IncomingScene extends AppCompatActivity implements View.OnClickListener{

    private String name,factory;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    Date incomingDate = new Date(System.currentTimeMillis());
    private TextView feed_date;
    private TextView crush_start;
    private TextView crush_end;
    private TextView mix_start;
    private TextView mix_end;
    private TextView feed_start;
    private TextView feed_end;
    private TextView deviceName;
    private TextView feed_weight;
    private TextView insect_residus_box_weight;
    private TextView box_weight;
    String activeButton = new String();
    Calendar calendar= Calendar.getInstance(Locale.CHINA);

    private SharedPreferences preferences;
    private ItemAdapter batchAdapter;
    private ItemAdapter groupAdapter;
    private List<String> batchList;
    private List<String> groupList;
    private EditText batch;
    private EditText group;
    private EditText boxNumber;
    private EditText remark;
    private PopupWindow batchPopupWindow;
    private PopupWindow groupPopupWindow;
    private TitleBar titleBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.incoming_scene);
        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                IncomingScene.this.finish();
            }
            @Override
            public void onTitleClick(View v) {
            }
            @Override
            public void onRightClick(View v) {
            }
        });
        /**
         * 显示设置日期
         */
        feed_date = findViewById(R.id.incoming_scene_feedDate);
        feed_date.setText(simpleDateFormat.format(incomingDate));
        /**
         * 仨重量
         */
        //加料重量
        feed_weight = findViewById(R.id.feedWeight);
        //大虫及渣加盒重
        insect_residus_box_weight = findViewById(R.id.insectResidusBoxWeight);
        //培育盒重
        box_weight = findViewById(R.id.boxWeight);
        /**
         * 六个时间
         */
        crush_start = (TextView) findViewById(R.id.crush_start);
        crush_start.setOnClickListener(this);
        crush_end = (TextView) findViewById(R.id.crush_end);
        crush_end.setOnClickListener(this);
        mix_start = (TextView) findViewById(R.id.mix_start);
        mix_start.setOnClickListener(this);
        mix_end = (TextView) findViewById(R.id.mix_end);
        mix_end.setOnClickListener(this);
        feed_start = (TextView) findViewById(R.id.feed_start);
        feed_start.setOnClickListener(this);
        feed_end = (TextView) findViewById(R.id.feed_end);
        feed_end.setOnClickListener(this);

        deviceName = (TextView) findViewById(R.id.incoming_scene_deviceName);
        remark = findViewById(R.id.incoming_scene_remark);
        /**
         *两个输入记录缓存
         */
        batch = findViewById(R.id.incoming_scene_batch);
        group = findViewById(R.id.incoming_scene_group);
        boxNumber = findViewById(R.id.incoming_scene_number);
        preferences = getSharedPreferences("incoming_scene", Context.MODE_PRIVATE);
        batchList = new ArrayList<>(preferences.getStringSet("batchList", new HashSet<>()));
        groupList = new ArrayList<>(preferences.getStringSet("groupList", new HashSet<>()));
        List<Item> batchItemList = new ArrayList<>();
        List<Item> groupItemList = new ArrayList<>();
        // Item类型list初始化
        for (String itemName : batchList) {
            batchItemList.add(new Item(itemName, R.drawable.ic_clear));
        }
        for (String itemName : groupList) {
            groupItemList.add(new Item(itemName, R.drawable.ic_clear));
        }

        // 创建ListView
        batchAdapter = new ItemAdapter(this, R.layout.adapter_item, batchItemList);
        groupAdapter = new ItemAdapter(this, R.layout.adapter_item, groupItemList);
        ListView batchListView = new ListView(this);
        batchListView.setAdapter(batchAdapter);
        batchListView.setOnItemClickListener((parent, view, position, id) -> {
            // 若有进行删除操作，更新nameList，否则nameList序号对不上
            if (batchAdapter.getDeletePos() >= 0) {
                List<Item> tempItemList = batchAdapter.getList();
                batchList.clear();
                for (Item item : tempItemList) {
                    batchList.add(item.getName());
                }
            }
            // 根据所选设置输入框文本
            String result = batchList.get(position);
            batch.setText(result);
            batchPopupWindow.dismiss();
            hideInput();
        });

        ListView groupListView = new ListView(this);
        groupListView.setAdapter(groupAdapter);
        groupListView.setOnItemClickListener((parent, view, position, id) -> {
            // 若有进行删除操作，更新nameList，否则nameList序号对不上
            if (groupAdapter.getDeletePos() >= 0) {
                List<Item> tempItemList = groupAdapter.getList();
                groupList.clear();
                for (Item item : tempItemList) {
                    groupList.add(item.getName());
                }
            }
            // 根据所选设置输入框文本
            String result = groupList.get(position);
            group.setText(result);
            groupPopupWindow.dismiss();
            hideInput();
        });


        // 获取屏幕的宽度并设置popupwindow的宽度为width,这里是根据布局控件所占的权重
        WindowManager wManager = (WindowManager) getSystemService(this.WINDOW_SERVICE);
        int width = wManager.getDefaultDisplay().getWidth() * 3 / 5;
        int height = wManager.getDefaultDisplay().getHeight() / 8;
        // 参数为 1.View 2.宽度 3.高度
        batchPopupWindow = new PopupWindow(batchListView ,width, height);
        // 设置点击外部区域可以取消popupWindow
        batchPopupWindow.setOutsideTouchable(true);

        batch.setOnFocusChangeListener((v, hasFocus) -> {
            // 设置popupWindow显示,并且告诉它显示在那个View下面
            if (hasFocus) {
                // 若聚焦到该输入框，显示下拉列表
                batchPopupWindow.showAsDropDown(batch);
            }
        });

        groupPopupWindow = new PopupWindow(groupListView ,width, height);
        // 设置点击外部区域可以取消popupWindow
        groupPopupWindow.setOutsideTouchable(true);

        group.setOnFocusChangeListener((v, hasFocus) -> {
            // 设置popupWindow显示,并且告诉它显示在那个View下面
            if (hasFocus) {
                // 若聚焦到该输入框，显示下拉列表
                groupPopupWindow.showAsDropDown(group);
            }
        });

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/research/feed/getlast";
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            Log.d("jy",response.toString());
                            JSONObject data;
                            if(jsonObject.get("data")!=null && !jsonObject.get("data").toString().equals("null")){
                                data = jsonObject.getJSONObject("data");
                                if (!data.isNull("id")) {
                                    feed_date.setText(data.getString("feedDate"));
                                    crush_start.setText(data.getString("crushStarttime"));
                                    crush_end.setText(data.getString("crushEndtime"));
                                    mix_start.setText(data.getString("mixStarttime"));
                                    mix_end.setText(data.getString("mixEndtime"));
                                    feed_start.setText(data.getString("feedStarttime"));
                                    feed_end.setText(data.getString("feedEndtime"));
                                    deviceName.setText(data.getString("deviceName"));
                                    batch.setText(data.getString("batch"));
                                    group.setText(data.getString("zubie"));
                                    boxNumber.setText(data.getString("boxNumber"));
                                    feed_weight.setText(data.getString("feedWeight"));
                                    insect_residus_box_weight.setText(data.getString("insectResidusBoxWeight"));
                                    box_weight.setText(data.getString("boxWeight"));
                                    remark.setText(data.getString("remark"));
                                    Toast.makeText(IncomingScene.this,
                                            "今日已填写此表", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
                                Date current_time = new Date(System.currentTimeMillis());
                                String current_time_string = simpleDateFormat.format(current_time);
                                crush_start.setText(current_time_string);
                                crush_end.setText(current_time_string);
                                mix_start.setText(current_time_string);
                                mix_end.setText(current_time_string);
                                feed_start.setText(current_time_string);
                                feed_end.setText(current_time_string);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(IncomingScene.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map=new HashMap<>();
                map.put("factory", factory);
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    /**
     * 提交内容并设置输入缓存
     * @param view
     */
    public void save(View view) {
        if (crush_start.getText().toString().equals("")) {
            Toast.makeText(this, "请填写粉碎开始时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (crush_end.getText().toString().equals("")) {
            Toast.makeText(this, "请填写粉碎结束时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mix_start.getText().toString().equals("")) {
            Toast.makeText(this, "请填写混料开始时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mix_end.getText().toString().equals("")) {
            Toast.makeText(this, "请填写混料结束时间", Toast.LENGTH_SHORT).show();
            return;
        }if (feed_start.getText().toString().equals("")) {
            Toast.makeText(this, "请填写进料开始时间", Toast.LENGTH_SHORT).show();
            return;
        }if (feed_end.getText().toString().equals("")) {
            Toast.makeText(this, "请填写进料结束时间", Toast.LENGTH_SHORT).show();
            return;
        }if (((TextView) findViewById(R.id.incoming_scene_deviceName)).getText().toString().equals("")) {
            Toast.makeText(this, "请填写设备名称", Toast.LENGTH_SHORT).show();
            return;
        }if ( ((TextView) findViewById(R.id.incoming_scene_batch)).getText().toString().equals("")) {
            Toast.makeText(this, "请填写批次", Toast.LENGTH_SHORT).show();
            return;
        }if (((TextView) findViewById(R.id.incoming_scene_group)).getText().toString().equals("")) {
            Toast.makeText(this, "请填写组别", Toast.LENGTH_SHORT).show();
            return;
        }if (((TextView) findViewById(R.id.incoming_scene_number)).getText().toString().equals("")) {
            Toast.makeText(this, "请填写编号", Toast.LENGTH_SHORT).show();
            return;
        }if (feed_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写加料重量", Toast.LENGTH_SHORT).show();
            return;
        }if (insect_residus_box_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写大虫及渣盒重", Toast.LENGTH_SHORT).show();
            return;
        }if (box_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写培育盒重", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
            .setTitle("确定保存吗？")
            .setCancelable(false)
            .setNegativeButton("取消", ((dialog, which) ->
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
            .setPositiveButton("确定", (dialog, which) -> {
                //输入缓存
                SharedPreferences.Editor editor = preferences.edit();
                // 若有进行删除操作，更新batchList
                List<Item> tempBatchList = batchAdapter.getList();
                if (tempBatchList.size() != batchList.size()) {
                    batchList.clear();
                    for (Item item : tempBatchList) {
                        batchList.add(item.getName());
                    }
                }
                // 判断该输入框内容是否已存在，不存在则加入
                String currentBatch = batch.getText().toString();
                if (!currentBatch.equals("") && !batchList.contains(currentBatch)) {
                    batchList.add(currentBatch);
                }

                //若有进行删除操作，更新groupList
                List<Item> tempGroupList = groupAdapter.getList();
                if (tempGroupList.size() != groupList.size()) {
                    groupList.clear();
                    for (Item item : tempGroupList) {
                        groupList.add(item.getName());
                    }
                }
                // 判断该输入框内容是否已存在，不存在则加入
                String currentGroup = group.getText().toString();
                if (!currentGroup.equals("") && !groupList.contains(currentGroup)) {
                    groupList.add(currentGroup);
                }

                editor.putStringSet("batchList", new HashSet<>(batchList));
                editor.putStringSet("groupList", new HashSet<>(groupList));
                editor.apply();


                //提交请求
                incomingDate = new Date(System.currentTimeMillis());
                RequestQueue queue = Volley.newRequestQueue(this);
                String url = Config.url + "/research/feed/add";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.d("jy", response);
                                if (response.toString().equals("true"))
                                    Toast.makeText(IncomingScene.this,
                                            "保存成功", Toast.LENGTH_SHORT).show();
                                else
                                    Toast.makeText(IncomingScene.this,
                                            "保存失败", Toast.LENGTH_SHORT).show();
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(IncomingScene.this, "保存失败", Toast.LENGTH_SHORT).show();
                        Log.d("jy", error.toString());
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> map=new HashMap<>();
                        map.put("feedDate", simpleDateFormat.format(incomingDate));
                        map.put("crushStarttime", crush_start.getText().toString());
                        map.put("crushEndtime", crush_end.getText().toString());
                        map.put("mixStarttime", mix_start.getText().toString());
                        map.put("mixEndtime", mix_end.getText().toString());
                        map.put("feedStarttime", feed_start.getText().toString());
                        map.put("feedEndtime", feed_end.getText().toString());
                        map.put("deviceName",  ((TextView) findViewById(R.id.incoming_scene_deviceName)).getText().toString());
                        map.put("batch", ((TextView) findViewById(R.id.incoming_scene_batch)).getText().toString());
                        map.put("zubie", ((TextView) findViewById(R.id.incoming_scene_group)).getText().toString());
                        map.put("boxNumber", ((TextView) findViewById(R.id.incoming_scene_number)).getText().toString());
                        map.put("feedWeight", feed_weight.getText().toString());
                        map.put("insectResidusBoxWeight", insect_residus_box_weight.getText().toString());
                        map.put("boxWeight", box_weight.getText().toString());
                        map.put("recorder",name);
                        map.put("remark", ((TextView) findViewById(R.id.incoming_scene_remark)).getText().toString());
                        return map;
                    }
                };
                stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                queue.add(stringRequest);
            })
            .show();
    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    /**
     * 时间选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showTimePickerDialog(Activity activity,int themeResId, final TextView tv, Calendar calendar) {
        // Calendar c = Calendar.getInstance();
        // 创建一个TimePickerDialog实例，并把它显示出来
        // 解释一哈，Activity是context的子类
        new TimePickerDialog( activity,themeResId,
                // 绑定监听器
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv.setText(String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute));
                    }
                }
                // 设置初始时间
                , calendar.get(Calendar.HOUR_OF_DAY)
                , calendar.get(Calendar.MINUTE)
                // true表示采用24小时制
                ,true).show();
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.crush_start:
                showTimePickerDialog(this,  2, crush_start, calendar);
                break;
            case R.id.crush_end:
                showTimePickerDialog(this,  2, crush_end, calendar);;
                break;
            case R.id.mix_start:
                showTimePickerDialog(this,  2, mix_start, calendar);;
                break;
            case R.id.mix_end:
                showTimePickerDialog(this,  2, mix_end, calendar);;
                break;
            case R.id.feed_start:
                showTimePickerDialog(this,  2, feed_start, calendar);;
                break;
            case R.id.feed_end:
                showTimePickerDialog(this,  2, feed_end, calendar);;
                break;
            default:
                break;
        }
    }

    /**
     * 称重接口
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        switch (activeButton){
            case "feedWeight_btn":
                feed_weight.setText(weight);
                break;
            case "insectResidusBoxWeight_btn":
                insect_residus_box_weight.setText(weight);
                break;
            case "boxWeight_btn":
                box_weight.setText(weight);
                break;
        }
    }
    public void goWeight(View view) {
        switch (view.getId()) {
            case R.id.feedWeight_btn:
                activeButton = "feedWeight_btn";
                break;
            case R.id.insectResidusBoxWeight_btn:
                activeButton = "insectResidusBoxWeight_btn";
                break;
            case R.id.boxWeight_btn:
                activeButton = "boxWeight_btn";
                break;
            default:
                break;
        }
        Intent intent = new Intent(IncomingScene.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }
}
